// const fs = require('fs')
// const path = require('path')
const webpack = require('webpack')

// 设置不参与构建的库
const externals = {}

const plugins = []
const transpileDependencies = []
const TerserPlugin = require('terser-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

const templateName = 'default'

// 拼接路径
const resolve = dir => require('path').join(__dirname, dir)

console.log('当前模板：' + templateName)

if (process.env.NODE_ENV === 'production') {
  plugins.push(
    // gzip
    new CompressionWebpackPlugin({
      filename: '[path].gz[query]',
      test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
      threshold: 10240,
      minRatio: 0.8,
      deleteOriginalAssets: false
    })
  )
}

plugins.push(
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)

module.exports = {
  outputDir: 'docker/web',
  configureWebpack: () => {
    const config = {}
    config.plugins = plugins
    config.optimization = {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: { drop_console: true, drop_debugger: true }
          }
        })
      ]
    }

    if (process.env.NODE_ENV === 'production') {
      config.externals = externals
    }
    if (process.env.NODE_ENV === 'development') {
      // 关闭 host check，方便使用 ngrok 之类的内网转发工具
      config.devServer = {
        disableHostCheck: true
      }
    }
    return config
  },
  css: {
    loaderOptions: {
      /* less: {
        lessOptions: {
          modifyVars: {
            'hack': `true; @import "${vars}"`
          }
        }
      }, */
      scss: {
        additionalData: `@import '~@/template/${templateName}/assets/style/mixins.scss';`
      },
      postcss: {
        plugins: [
        ]
      }
    }
  },
  chainWebpack: config => {
    config.resolve.alias
      .set('@images', resolve(`src/template/${templateName}/assets/images`))
      .set('@router', resolve(`src/template/${templateName}/router`))
    /**
     * 删除懒加载模块的 prefetch preload，降低带宽压力
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#prefetch
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#preload
     * 而且预渲染时生成的 prefetch 标签是 modern 版本的，低版本浏览器是不需要的
     */
    config.plugins
      .delete('prefetch')
      .delete('preload')
  },
  // 不输出 map 文件
  productionSourceMap: false,
  transpileDependencies,
  devServer: {
    // port: 8997
  }
}
